import React from 'react';

export default class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { error: null, errorInfo: null };
    if (props.message) {
      this.message = props.message;
    } else {
      this.message = '发生了一些错误,请尝试后退到上一页面或者刷新';
    }

    this.error = props.error;
    this.redirect = props.redirect;
  }

  componentDidCatch(error, errorInfo) {
    // Catch errors in any components below and re-render with error message
    this.setState({
      error: error,
      errorInfo: errorInfo,
    });
    // 你同样可以将错误日志上报给服务器
  }

  render() {
    if (this.state.errorInfo) {
      // 你可以自定义降级后的 UI 并渲染
      return (
        <div>
          {this.error ? this.error : null}
          {this.message ? this.message : null}
          {this.redirect ? this.redirect : null}
          <details style={{ whiteSpace: 'pre-wrap' }}>
            {this.state.error && this.state.error.toString()}
            <br />
            {this.state.errorInfo.componentStack}
          </details>
        </div>
      );
    }
    // Normally, just render children
    return this.props.children;
  }
}
